package czx.wt.web.shiro;

import czx.wt.pojo.SysUser;
import czx.wt.service.ISysUserService;
import czx.wt.util.ServletUtils;
import czx.wt.util.ValidateUtil;
import czx.wt.web.common.UserConstants;
import czx.wt.web.common.UserStatus;
import czx.wt.web.exception.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * @Description: 登录校验方法
 * @Author: ChenZhiXiang
 * @CreateDate: 2019/2/12 0012 14:30
 * @Version: 1.0
 */
@Service
public class SysLoginService {

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录
     */
    public SysUser login(String username,String password){
        // 验证码校验
        if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))){
            throw new CaptchaException();
        }
        // 用户名或密码为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw new UserNotNullException();
        }
        //匹配小写字母、大写字母、数字、特殊符号的两种及两种以上【非中文】，长度6到16位
        if (!ValidateUtil.isPassword(password)){
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
        // 查询用户信息
        SysUser user = userService.selectUserByLoginName(username);

        if (user == null)
        {
            throw new UserNotExistsException();
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            throw new UserDeleteException();
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            throw new UserBlockedException();
        }

        passwordService.validate(user, password);
        return user;
    }
}
